package Controller;

import Data.FriendListData;
import Data.PrivateInformationData;
import Data.RegisterData;
import Data.event;
import MyInterfaces.MassageType;
import Service.ClientConnectionServer;
import Service.GetMassage;
import Service.Main;
import Service.SendMassage;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;

import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class RegisterController {

    @FXML
    private TextField emailNumber;

    @FXML
    private Button submitButton;

    @FXML
    private TextField accountName;

    @FXML
    private TextField textpassword1;

    @FXML
    private TextField captcha;

    @FXML
    private Button closeButton;

    @FXML
    private TextField textpassword2;

    @FXML
    private Button getCaptcha;

    @FXML
    private PasswordField passwordField;

    @FXML
    private Button cansee1;

    @FXML
    private Button cansee2;

    @FXML
    private PasswordField ensurepasswordField;

    @FXML
    private Button notsee2;

    @FXML
    private Button notsee1;

    private ObjectOutputStream writer;
    private ObjectInputStream reader;

    String userNumber;
    @FXML
    String email;
    String userPwd;
    String ensurePwd;

    String yzm=null;
    private static Socket socket;

    private static Date predate=new Date();

    public RegisterController() throws IOException {
    }

    public static void init(Socket socket) throws IOException {
        RegisterController.socket=socket;
        predate.setTime(predate.getTime()-60*1000);
    }

    @FXML
    //注册
    private void registerOperation() throws Exception {

    }

    @FXML
    void close(MouseEvent event) throws IOException {
        event massage=new event();
        massage.setType(MassageType.Exit);

        new SendMassage().sendMassage(massage);

        Stage stage = (Stage) closeButton.getScene().getWindow();
        stage.close();
    }

    public void submitAction(ActionEvent actionEvent) throws Exception {
        userNumber = accountName.getText();
        email = emailNumber.getText();
        if(textpassword1.isVisible()) userPwd = textpassword1.getText();
        else userPwd = passwordField.getText();
        if(textpassword2.isVisible()) ensurePwd=textpassword2.getText();
        else ensurePwd = ensurepasswordField.getText();
        if(userNumber.equals("")||userPwd.equals("")||email.equals("")||captcha.getText().equals(""))
        {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("错误");
            alert.setHeaderText(null);
            alert.setContentText("用户名或者密码，邮件，验证码不可以为空!");
            alert.showAndWait();
            return ;
        }
        if (userPwd.equals(ensurePwd)) {
            //如果密码一致，需要正则表达式判断
            String pwdPattern ="^(?=.*\\d)(?=.*[a-zA-Z])(?=.*[^\\da-zA-Z\\s]).{8,16}$";
            Pattern p=Pattern.compile(pwdPattern);
            Matcher m=p.matcher(userPwd);
            if(m.find())
            {
                //通过了正则表达式
                System.out.println("可以");
            }
            else
            {
                System.out.println(userPwd);
                System.out.println(pwdPattern);
                //没有通过
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("错误");
                alert.setHeaderText(null);
                alert.setContentText("密码强度不够，必须是8-16位，需要有字母，数字，和特殊字符^_^");
                alert.showAndWait();
                return ;
            }
            System.out.println("密码一致");
        } else {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("错误");
            alert.setHeaderText(null);
            alert.setContentText("密码俩次不一致");
            alert.showAndWait();
            System.out.println("密码不一致");
            return ;
        }

        //发送注册的消息
        event massage=new event();
        massage.setType(MassageType.Request_Register);
        RegisterData registerData=new RegisterData(userNumber,email,captcha.getText(),userPwd);
        massage.setT(registerData);
        SendMassage send=new SendMassage();
        send.sendMassage(massage);
        System.out.println("发送注册消息完成");

        //得到一个消息
        event returnmassage=new GetMassage().getMassage();

        if(returnmassage.getType().equals(MassageType.Return_Register_Success))
        {
            //注册成功
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("成功");
            alert.setHeaderText(null);
            alert.setContentText("注册成功!");
            alert.showAndWait();

            Stage thisstage=(Stage) submitButton.getScene().getWindow();
            thisstage.close();

            //直接进入主界面
            FriendListData friendListData=(FriendListData) returnmassage.getT();
            ArrayList<PrivateInformationData> friendlist=friendListData.getFriendList();
            PrivateInformationData mydata=friendListData.getMydata();

            Stage stage=new Stage();
            File file=new File("E:\\JDK\\QQClient\\nox\\src\\fxml\\ChatMain.fxml");
            URL location =file.toURI().toURL();
            FXMLLoader fxmlLoader=new FXMLLoader();
            fxmlLoader.setLocation(location);
            Parent root=fxmlLoader.load();
            stage.setTitle("主界面");
            stage.setResizable(false);
            stage.setScene(new Scene(root,400,700));
            stage.show();

            Main.AllContronller.setChatMainController(fxmlLoader.getController());
            Main.AllContronller.getChatMainController().setSocket(socket);
            Main.AllContronller.getChatMainController().setChatStage(mydata,friendlist);

            Thread myThread=new Thread(new ClientConnectionServer(socket,mydata.getUserid()));
            myThread.start();
        }
        else if(returnmassage.getType().equals(MassageType.Return_Register_Fail))
        {
            //注册失败
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("错误");
            alert.setHeaderText(null);
            alert.setContentText("邮箱和验证码错误（和你之前获取的邮箱号和验证码不符合，或者验证码已经过期）!");
            alert.showAndWait();

        }
    }

    public void getcaptcha(ActionEvent actionEvent) throws Exception {

        String emailPattern="^([A-Za-z0-9_\\-\\.])+\\@([A-Za-z0-9_\\-\\.])+\\.([A-Za-z]{2,4})$";
        Pattern p=Pattern.compile(emailPattern);
        Matcher m=p.matcher(emailNumber.getText());
        if(m.find())
        {
            System.out.println("邮箱可以的");
            Date nowdate=new Date();
            if((nowdate.getTime()-predate.getTime())< 60 * 1000)
            {
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("错误");
                alert.setHeaderText(null);
                alert.setContentText("一分钟内不可以重复点击获取验证码!");
                alert.showAndWait();
                return ;
            }
            //发送获得验证码的消息
            event massage=new event();
            massage.setType(MassageType.Get_Captcha);
            massage.setT(new String(emailNumber.getText()));
            new SendMassage().sendMassage(massage);

            predate=new Date();
            System.out.println("发送成功");

        }
        else
        {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("错误");
            alert.setHeaderText(null);
            alert.setContentText("邮箱格式错误");
            alert.showAndWait();
            return ;
        }

    }

    public void CanSeeAction1(ActionEvent actionEvent) {
        cansee1.setVisible(false);
        textpassword1.setVisible(false);
        notsee1.setVisible(true);
        passwordField.setText(textpassword1.getText());
        passwordField.setVisible(true);
    }

    public void NotSeeAction1(ActionEvent actionEvent) {
        cansee1.setVisible(true);
        textpassword1.setText(passwordField.getText());
        textpassword1.setVisible(true);
        notsee1.setVisible(false);
        passwordField.setVisible(false);
    }

    public void CanSeeAction2(ActionEvent actionEvent) {
        cansee2.setVisible(false);
        textpassword2.setVisible(false);
        notsee2.setVisible(true);
        ensurepasswordField.setText(textpassword2.getText());
        ensurepasswordField.setVisible(true);
    }

    public void NotSeeAction2(ActionEvent actionEvent) {
        cansee2.setVisible(true);
        textpassword2.setText(ensurepasswordField.getText());
        textpassword2.setVisible(true);
        notsee2.setVisible(false);
        ensurepasswordField.setVisible(false);
    }
}
